<?php
namespace app\upapi\controller;

use think\Controller;

/**
 * 通用上传接口
 * Class Upload
 * @package app\api\controller
 */
class Chatupload extends Controller
{
    private $wx_user;
    private $author_wx_user;
    private $wechatObj;

    protected function _initialize()
    {
        parent::_initialize();
    }

    /**
     * 通用图片上传接口
     * @return \think\response\Json
     */
    public function upload($file)
    {
        $config = [
            'size' => 2097152,
            'ext'  => 'jpg,gif,png,bmp'
        ];

        $upload_path = str_replace('\\', '/', ROOT_PATH . 'public/uploads');
        $save_path   = '/uploads/'; 
        $info        = $file->validate($config)->move($upload_path);

        if ($info) {
            $result = [
                'error' => 0,
                'url'   => str_replace('\\', '/', $save_path . $info->getSaveName())
            ];
        } else {
            $result = [
                'error'   => 1,
                'message' => $file->getError()
            ];
        }

        return $result;
    }

    public function UnifiedUpload(){
        $file = $this->request->file('image');
        $result = $this->upload($file);
        return json($result);
    }

    /**
     * 通用图片上传接口
     * @return \think\response\Json
     */
    public function voiceUpload($file)
    {
        $config = [
            'size' => 2097152,
            'ext'  => 'amr,speex,mp3,wav'
        ];

        $upload_path = str_replace('\\', '/', ROOT_PATH . 'public/uploads');
        $save_path   = '/uploads/';
        $info        = $file->validate($config)->move($upload_path);

        if ($info) {
            $result = [
                'error' => 0,
                'url'   => str_replace('\\', '/', $save_path . $info->getSaveName())
            ];
        } else {
            $result = [
                'error'   => 1,
                'message' => $file->getError()
            ];
        }

        return $result;
    }

    /**
     * 网络图片保存本地
     * @return \think\response\Json
     */
    function saveChatImage($path) {
        $save_path = './uploads/'.date('Ymd').'/';
        if(!file_exists($save_path)){
            mkdir($save_path,0777,true);
        }
        $image_name = $save_path.base64_encode(date('H:i:s').rand(1000,9999)).'.arm';
        $ch = curl_init($path);
        curl_setopt($ch, CURLOPT_RETURNTRANSFER, 1);
        curl_setopt($ch, CURLOPT_BINARYTRANSFER,1);
        $img = curl_exec ($ch);
        curl_close ($ch);
        $fp = fopen($image_name,'w');
        fwrite($fp, $img);
        fclose($fp);
        return ['path'=>substr($image_name,1)];
    }
}